package com.ztesoft.sca.thread;

import com.ztesoft.sca.common.BeanFactory;
import com.ztesoft.sca.dao.IomManageDao;
import com.ztesoft.sca.dao.IomManageDaoImpl;
import com.ztesoft.sca.dao.ThreadManageDao;
import com.ztesoft.sca.dao.ThreadManageDaoImpl;
import com.ztesoft.sca.model.AudioSourceDto;
import com.ztesoft.sca.service.IvrConvertService;
import com.ztesoft.sca.service.IvrConvertServiceImpl;
import com.ztesoft.sca.thread.threadFactory.IvrConverThreadFactory;
import com.ztesoft.sca.thread.threadPool.IvrConvertThreadPool;
import org.apache.commons.collections.MapUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;

public class IvrListRunnable implements Runnable {

	private static Logger logger = Logger.getLogger(IvrListRunnable.class);

    private IvrConvertService ivrConvertService;

    private static ExecutorService ivrConvertThreadPool;

    static {
		try {
			BlockingQueue workQueue = new LinkedBlockingQueue<IvrConvertRunnable>(100000);
			ThreadFactory ivrConvertThreadFactory = new IvrConverThreadFactory();
			RejectedExecutionHandler reject =  new ThreadPoolExecutor.AbortPolicy();//默认终止策略，当队列满的时候直接抛出异常
			ivrConvertThreadPool = new IvrConvertThreadPool(5,10,120,TimeUnit.SECONDS,workQueue,ivrConvertThreadFactory,reject);

		} catch (Exception e) {
			logger.error("IvrConvertRunnable INIT ERROR :",e);
		}

	}

	@Override
	public void run() {
			try {
				logger.info(" ****进入ListRunnable  ");
                ivrConvertService = BeanFactory.lookUp(IvrConvertServiceImpl.class );
				List<Map> ivrOrderList = ivrConvertService.listIvrRecord();
				if (null != ivrOrderList && ivrOrderList.size() > 0) {
					logger.info("本次查询待转换ivr工单:" + ivrOrderList.size() + "条");
					for (int i=0; i<ivrOrderList.size();i++){
					    Map orderMap=ivrOrderList.get(i);
						ivrConvertThreadPool.execute(new IvrConvertRunnable(orderMap));
                        ivrConvertService.addIomConvertRecord(orderMap);
                    }
				}else{
                    logger.info(" 本次查询待转换ivr工单为0  ");
                }
			} catch (Throwable e) {
				logger.error("转换ivr线程异常," + e.getMessage(), e);
				e.printStackTrace();
			}
	}
}
